package com.focusai.efairy.network;

import com.focusai.efairy.utils.log.Log;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by heqingbao on 2016/7/22.
 */
public class LoggingInterceptor implements Interceptor {
    private static final String TAG = LoggingInterceptor.class.getSimpleName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        StringBuilder sb = new StringBuilder(" params[");
        RequestBody requestBody = request.body();
        if (requestBody instanceof FormBody) {
            FormBody formBody = (FormBody) requestBody;
            for (int i = 0, size = formBody.size(); i < size; i++) {
                sb.append(formBody.name(i)).append(":").append(formBody.value(i)).append(" ");
            }
        }

        sb.append(" | header: ").append(request.headers().toString().replace("\n", " ")).append("]");

        Log.I(TAG,String.format("发送请求 %s %s", request.url(), sb.toString()));

        long t1 = System.nanoTime();
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();

        Log.I(TAG,String.format("请求完成 %s in %.1fms", response.request().url(), (t2 - t1) / 1e6d));

        return response;
    }

    @Override
    public String toString() {
        // 防止混淆后不方便查看Log
        return "LoggingInterceptor@" + Integer.toHexString(hashCode());
    }
}
